'''
Created on Nov 24, 2012

@author: trananh
'''
import math


def median(numbers):
    """
    Return the median value for the list of numbers.
    If there is an even number of elements, then average the middle two.
    
    PARAMETERS:
        numbers - list of numbers. 
    """
    n = len(numbers)
    copy = numbers[:]
    copy.sort()
    if n % 2 == 1:
        return copy[n // 2]
    else:
        return (copy[n // 2 - 1] + copy[n // 2]) / 2.0


def mean(numbers):
    """
    Return the arithmetic average of the list of numbers.
    
    PARAMETERS:
        numbers - list of numbers. 
    """
    return sum(numbers) / float(len(numbers))


def entropy(distribution):
    """
    Return the entropy of the given distribution (or histogram).
    
    PARAMETERS:
        distribution - list of numbers representing some distribution.
    """
    total = sum(distribution)
    N = distribution if total == 1 else [float(x)/total for x in distribution]
    return sum([-p*math.log(p) if p > 0 else 0 for p in N])
